/*
 * Copyright (C) 2024 HiHope Open Source Organization.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import createOrGet from '../utils/SingleInstanceHelper';
import { Log } from '../utils/Log';
import { Callback } from '@ohos.base';
import { common } from '@kit.AbilityKit';
import { preferences, ValueType } from '@kit.ArkData';

const TAG: string = 'PreferenceManager';
const PREFERENCE_NAME = 'SHARE_PREFS';

export class PreferenceManager {
  mPrefs: preferences.Preferences | undefined = undefined;

  init(context: common.ServiceExtensionContext) {
    preferences.getPreferences(context, PREFERENCE_NAME).then((prefs: preferences.Preferences) => {
      this.mPrefs = prefs;
    })
  }

  getValueSync(key:string, defaultValue: preferences.ValueType): preferences.ValueType {
    let result:preferences.ValueType = this.mPrefs?.getSync(key,defaultValue);
    Log.info(TAG, `getValueSync, key = ${key}, result = ${result}, typeof result = ${typeof result}`);
    return result;
  }

  async setValueSync(key: string, value: preferences.ValueType) {
    Log.info(TAG, `setValueSync, key = ${key}, value = ${value}`);
    this.mPrefs?.putSync(key, value);
    await this.mPrefs?.flush();
  }

  release() {
    this.mPrefs?.flush();
    this.mPrefs = undefined;
  }
}

const sPreferenceManager: PreferenceManager = createOrGet(PreferenceManager, 'PreferenceManager');

export default sPreferenceManager;